package be.idamf.cortizone.fileprocessor
{
	import be.idamf.flash.events.dispatchEventOn;
	
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	
	import mx.collections.ArrayCollection;
	
	[Event(name="progress", type="flash.events.ProgressEvent")]
	[Event(name="complete", type="flash.events.Event")]
	
	public class FileProcessorAsync extends EventDispatcher implements IFileProcessor
	{
		private var _isBusy:Boolean;
		[Bindable]
		public function get isBusy():Boolean
		{
			return _isBusy;
		}
		private function set isBusy(value:Boolean):void
		{
			_isBusy = value;
		}
		
		private var _current:int;
		[Bindable]
		public function get current():int
		{
			return _current;
		}
		private function set current(value:int):void
		{
			_current = value;
		}

		private var _total:int;
		[Bindable]
		public function get total():int
		{
			return _total;
		}
		private function set total(value:int):void
		{
			_total = value;
		}
		
		[Bindable]
		public var result:ArrayCollection;
		
		protected var file:File;
		protected var files:Array;
		
		public function FileProcessorAsync()
		{
		}
		
		public function reset():void
		{
			files = [];
			current = 0;
			total = 0;
			
			result = new ArrayCollection();
		}
		
		public function cancel():void
		{
			files = [];
		}
		
		public function process(file:File):Boolean
		{
			files.push(file);
			total++;
			
			if (!isBusy)
				proceed();
			
			return true;
		}
		
		protected function proceed():void
		{
			dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, current, total));
			
			if (files.length == 0)
			{
				isBusy = false;
				dispatchEventOn(this, Event.COMPLETE);
				return;
			}
			
			file = files.shift();
			current++;
			
			processAsync();
			
			isBusy = true;
		}
		
		protected function processAsync():void
		{
			throw new Error("Abstract Method");
		}
	}
}